﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LuaInterface;
using System;

public class TroopHero : MonoBehaviour {
    public Troop m_troop;
    public GameObject m_Model;
    private Animation m_Animation;
    private string _nowAction;

    private bool bLeft = false;

    private string heroType = "";

    public void Init(Troop troop,string _heroType) 
    {
        m_troop = troop;
        m_Animation = GetComponentInChildren<Animation>(true);
        m_Model = gameObject;
        heroType = _heroType;
        PlayAni(BattleSettings._heroActionIdle,lrAngle(),true);
    }

    public Vector3 Pos()
    {
        return transform.position;
    }

    public void PlayAni(string action,float eulerAngle,bool isLoop,bool mustRest =false) 
    {
        string clipName = heroType + "@" + action;

        if (_nowAction != action || mustRest)
        {
            if (m_Animation.GetClip(clipName) != null)
            {
                if (mustRest)
                    m_Animation.Stop();

                m_Animation.wrapMode = isLoop ? WrapMode.Loop : WrapMode.Once;
                m_Animation.Play(clipName);
                _nowAction = action;
                m_Model.transform.localEulerAngles = new Vector3(0, eulerAngle, 0);
            }
        }
    }

    public void DoAttack() 
    {
        PlayAni(BattleSettings._heroActionA1, lrAngle(),false);
        BattleMgr.Instance.AddInterval(AniFinish, GetClipLength(BattleSettings._heroActionA1));
    }

    public void DoSkill() 
    {
        PlayAni(BattleSettings._heroActionS1,lrAngle(),false,true);
        BattleMgr.Instance.AddInterval(AniFinish, GetClipLength(BattleSettings._heroActionS1));
    }

    public void DoDead() 
    {
        PlayAni(BattleSettings._heroActionDie,lrAngle(),false);
    }


    public void AttckBySkill() 
    {
        PlayAni(BattleSettings._heroActionHurt,lrAngle(),false);
        BattleMgr.Instance.AddInterval(AniFinish, GetClipLength(BattleSettings._heroActionHurt));
    }

    //所有的一次性动画播放完毕之后的毁掉
    private void AniFinish()
    {
        if (!_nowAction.Equals(BattleSettings._heroActionDie)) 
        {
            PlayAni(BattleSettings._heroActionIdle, lrAngle(), true);
        }
    }

    private float GetClipLength(string clipName)
    {
        clipName = heroType + "@" + clipName;
        AnimationClip clip = m_Animation.GetClip(clipName);
        if (clip != null)
            return clip.length;
        else
            return 0;
    }

    private float lrAngle()
    {
        if (m_troop.IsLeft)
            return 0;
        else
            return 180;
    }
}
